<script setup>
import { ref, onMounted, nextTick, onUnmounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Document, Plus, Edit, Delete, Search } from '@element-plus/icons-vue'
import { useAdminStore } from '@/stores/admin'

const adminStore = useAdminStore()
const loading = ref(false)
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const chapterList = ref([])
const searchKey = ref('')
const elTableRef = ref(null)

const fetchChapters = async () => {
  try {
    loading.value = true
    const response = await adminStore.getChapterList({
      page: currentPage.value,
      pageSize: pageSize.value,
      search: searchKey.value
    })
    chapterList.value = response.items
    total.value = response.total
  } catch (error) {
    console.error('Failed to fetch chapters:', error)
    // 使用模拟数据
    chapterList.value = [
      {
        chapterID: 1,
        title: 'Vue3 基础入门',
        course: 'Vue3 入门到精通',
        status: 'active',
        createTime: '2024-01-01'
      },
      {
        chapterID: 2,
        title: 'Vue3 组件开发',
        course: 'Vue3 入门到精通',
        status: 'draft',
        createTime: '2024-01-02'
      }
    ]
    total.value = 2
    ElMessage({
      message: '获取章节列表失败，已显示模拟数据',
      type: 'warning',
      duration: 5 * 1000
    })
  } finally {
    loading.value = false
  }
}

const handleDelete = async (chapter) => {
  try {
    await ElMessageBox.confirm('确定要删除该章节吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    await adminStore.deleteChapter(chapter.chapterID)
    ElMessage.success('删除成功')
    fetchChapters()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  fetchChapters()
}

const handleSizeChange = (val) => {
  pageSize.value = val
  currentPage.value = 1
  fetchChapters()
}

const handleSearch = () => {
  currentPage.value = 1
  fetchChapters()
}

// 定义 handleResize 函数，以便在 onUnmounted 中正确移除监听器
const handleResize = () => {
  if (elTableRef.value) {
    elTableRef.value.doLayout()
  }
}

onMounted(() => {
  fetchChapters()
  nextTick(() => {
    if (elTableRef.value) {
      elTableRef.value.doLayout()
    }
  })

  window.addEventListener('resize', handleResize)
})

onUnmounted(() => {
  window.removeEventListener('resize', handleResize)
})
</script>

<template>
  <div class="chapter-management">
    <el-card>
      <template #header>
        <div class="card-header">
          <span style="font-size: 20px; font-weight: bold; display: flex; align-items: center; white-space: nowrap; flex-grow: 1; flex-shrink: 0;" >
            <el-icon style="margin-right: 8px; color: #1976d2"><Document /></el-icon>
            章节管理
          </span>
          <div class="search-bar">
            <el-input
              v-model="searchKey"
              placeholder="搜索章节名称"
              clearable
              @keyup.enter="handleSearch"
              style="flex: 1; max-width: 220px; margin-right: 8px;"
            />
            <el-button type="primary" :icon="Search" @click="handleSearch">搜索</el-button>
          </div>
        </div>
      </template>

      <el-table
        v-loading="loading"
        :data="chapterList"
        style="width: 100%"
        border
        empty-text="暂无章节数据"
        ref="elTableRef"
        table-layout="fixed"
      >
        <el-table-column prop="title" label="章节名称" flex="1" />
        <el-table-column prop="course" label="所属课程" flex="1" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="row.status === 'active' ? 'success' : 'info'">
              {{ row.status === 'active' ? '已发布' : '草稿' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="180" />
        <el-table-column label="操作" width="200">
          <template #default="{ row }">
            <el-button
              type="primary"
              size="small"
              :icon="Edit"
              @click="handleEdit(row)"
            >
              编辑
            </el-button>
            <el-button
              type="danger"
              size="small"
              :icon="Delete"
              @click="handleDelete(row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
  </div>
</template>

<style scoped>
.chapter-management {
  padding: 0;
  width: 100%;
}

.el-card {
  width: 100% !important;
  border-radius: 12px;
  box-shadow: 0 2px 12px 0 rgba(0,0,0,0.04);
  padding: 20px;
}

.card-header {
  display: flex;
  align-items: center;
  padding-bottom: 8px;
  flex-wrap: wrap;
}

.search-bar {
  display: flex;
  align-items: center;
  flex-shrink: 0;
  min-width: 200px;
  margin-left: auto;
}

.pagination-container {
  margin-top: 24px;
  display: flex;
  justify-content: flex-end;
}

.el-table th {
  background: #f5f7fa;
  color: #34495e;
  font-weight: bold;
}

.el-table .el-tag {
  font-size: 13px;
}
</style> 